<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/29
 * Time: 17:03
 */

namespace Admin\Controller;

use Common\Common\ResponseResult;
use Common\Common\Validator;
use Common\Model\Auth;

class Controller extends \Think\Controller
{
    public function __construct()
    {
        parent::__construct();
        if (!Auth::check()) {
            header('location:/login');
            die();
        }
        Auth::updateUser();
        $this->assign('user', Auth::user());
    }

    /**
     *
     *
     * @param string $permission
     * @param string $role
     * @return bool
     */
    protected final function check($permission, $role)
    {
        $roles = Auth::user()->role();
        if (!($roles->is($role) && $roles->hasPermission($permission))) {
            $this->message();
        }
        return true;
    }

    /**
     *
     *
     * @param array $permission
     * @param string $role
     * @return bool
     */
    protected final function checks(array $permission, $role)
    {
        $roles = Auth::user()->role();
        if (!($roles->is($role) && $roles->hasPermissions($permission))) {
            $this->message();
        }
        return true;
    }

    /**
     * @param string $permission
     * @return bool
     */
    protected final function checkPermission($permission)
    {
        if (!Auth::user()->role()->hasPermission($permission)) {
            $this->message();
        }
        return true;
    }

    /**
     *
     *
     * @param array $permission
     * @return bool
     */
    protected final function checkPermissions(array $permission)
    {
        if (!Auth::user()->role()->hasPermissions($permission)) {
            $this->message();
        }
        return true;
    }

    protected final function message()
    {
        if (IS_AJAX) {
            ResponseResult::error(10000, '未授权');
        } else {
            $this->error('未授权', '/');
            die();
        }
    }

    /**
     * 重写 error方法
     *
     * @param string $message
     * @param string $jumpUrl
     * @param bool $ajax
     * @param Validator|null $validator
     */
    protected function error($message = '', $jumpUrl = '', $ajax = false, Validator $validator = null)
    {
        $temp = '';
        if ($validator != null && $validator->filed()) {
            foreach ($validator->error() as $key => $error) {
                $temp .= "<ul style='list-style: none'><p>$key:</p>";
                foreach ($error as $item) {
                    $temp .= "<li style='margin-left: 20px; color: red'>$item</li>";
                }
                $temp .= '</ul>';
            }
        }
        parent::error($temp . $message, $jumpUrl, $ajax);
    }
}